# coding: utf-8

import json
import uuid
from datetime import date

from flask import request, current_app
from flask_restful import Api, Resource

from app.api.codes import PARAMS_ILLEGAL
from app.extensions import im_sync_proxy, db
from app.api.ip_utils import ip_util
from app.op.constant import AreaType
from app.op.models import Area
from common.constant import ENTERPRISE_OFFER_CNT_KEY, ENTERPRISE_OFFER_CNT_KEY_TIMEOUT
from app.utils import get_root_host_name
from common.im_util import im_client, IMMessageType
from .enterprise_schemas import enterprise_schema, enterprise_im_schema
from app.enterprise.models import EnterpriseHomepage
from .views import Response
from .enterprise_codes import ENTERPRISE_NOT_EXISTED
from common.bid_notify.message import NotifyBase


api = Api()


@api.resource('/enterprise/homepage')
class EnterpriseHomepageResource(Resource):
    """
    add by zhouhl 2018-05-22
    返回企业推广首页相关信息
    """

    def get(self):
        # 默认值供测试使用
        hostname = get_root_host_name(request.referrer)
        enterprise_homepage = EnterpriseHomepage.get_by_args(hostname=hostname)

        if not enterprise_homepage:
            return Response(ENTERPRISE_NOT_EXISTED)

        # 生成一个缓存key
        key = ENTERPRISE_OFFER_CNT_KEY.format(
            id=enterprise_homepage.enterprise_id,
            date=date.today().strftime('%F')
        )
        cnt = current_app.redis.incr(key)
        if cnt == 1:
            # 首次写入缓存, 设置ttl
            current_app.redis.expire(key, ENTERPRISE_OFFER_CNT_KEY_TIMEOUT)

        # 访客的im信息
        has_im = request.args.get('has_im', '0')
        ip_info = ip_util.find(request.remote_addr)
        if has_im == '0':
            accid = uuid.uuid4().hex
            im_token = im_client.apply_im_token(accid)
            guest_im_info = {
                'accid': accid,
                'im_token': im_token
            }
            # 把城市同步到im信息中
            try:
                im_sync_proxy.send(json.dumps(dict(
                    func='update_user_info',
                    kwargs={
                        'accid': guest_im_info['accid'],
                        'city': ip_info[1],
                        'name': '{}客户'.format(
                            ip_info[1] if str(ip_info[1]) != 'nan' else ''
                        )
                    }
                )))
            except:
                pass
        else:
            guest_im_info = {
                'accid': '',
                'im_token': ''
            }

        # 根据ip地址取城市信息
        try:
            code = str(int(ip_info[2])) if ip_info.any() else '440304'
        except:
            code = '440304'

        prov = Area.get_by_args(id=code[:2] + '0000', type=AreaType.PROV.value)
        city = Area.get_by_args(id=code[:4] + '00', type=AreaType.CITY.value)

        if code.isdigit() and city and prov:
            ip_info = {
                'prov_id': prov.id,
                'prov': prov.name,
                'city_id': city.id,
                'city': city.name,
            }
        else:
            ip_info = {
                'prov_id': '440000',
                'prov': '广东省',
                'city_id': '440300',
                'city': '深圳市',
            }

        enterprise = enterprise_homepage.enterprise
        data = enterprise_schema.dump(enterprise)[0]
        data['offer_cnt'] = cnt
        data['guest_im_info'] = guest_im_info
        data['im_info'] = {
            'accid': enterprise.user_id,
            'nickname': enterprise_homepage.agent_name,
            'avatar': enterprise_homepage.agent_avatar_url
        }
        data['ip_info'] = ip_info
        return Response(info_dict=data)


@api.resource('/enterprise/send_im_message')
class EnterpriseImResource(Resource):
    """
    created by chenhj at 2018/5/29
    企业im发送信息
    """
    def post(self):
        """
        created by chenhj at 2018/5/29

        """
        data, errors = enterprise_im_schema.load(request.get_json())
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        NotifyBase.batch_send_app_message(
            db.session,
            data['from_id'],
            [data['to_id']],
            dict(msg=data['content'], type=0),
            IMMessageType.CHAT.value
        )

        return Response()
